﻿namespace ClassyBlog.Infrastructure
{
    using System;
    using System.Web.Mvc;

    using Web;

    public class ArchivedDatesBinder : IModelBinder
    {
        public object BindModel(
            ControllerContext controllerContext,
            ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException("bindingContext");
            }

            var year = Convert(
                bindingContext.ValueProvider
                .GetValue(ArchivedDates.YearParameterName));

            var month = Convert(
                bindingContext.ValueProvider
                .GetValue(ArchivedDates.MonthParameterName));

            var day = Convert(
                bindingContext.ValueProvider
                .GetValue(ArchivedDates.DayParameterName));

            return new ArchivedDates(year, month, day);
        }

        private static int? Convert(ValueProviderResult result)
        {
            return result == null ?
                   null :
                   (int?)result.ConvertTo(typeof(int?), Culture.Current);
        }
    }
}